/*
 * Classname ISSOClientTest.java
 *
 * Version information
 *
 * Date Mar 2, 2006
 * Copyright (c) AmSoft Systems, 2006
 */
package net.amsoft.iservice.isso.client.tests;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;

import org.apache.soap.Body;
import org.apache.soap.Envelope;
import org.apache.soap.Header;
import org.apache.soap.util.xml.XMLParserUtils;
import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import x0Protocol.oasisNamesTcSAML2.ArtifactDocument;
import x0Protocol.oasisNamesTcSAML2.ArtifactResolveDocument;
import x0Protocol.oasisNamesTcSAML2.ArtifactResolveType;
import x0Protocol.oasisNamesTcSAML2.ArtifactResponseDocument;
import x0Protocol.oasisNamesTcSAML2.AuthnRequestDocument;
import x0Protocol.oasisNamesTcSAML2.LogoutRequestDocument;

import net.amsoft.iservice.isso.client.ISSOClient;
import net.amsoft.iservice.isso.client.SAMLDataObject;

import junit.framework.TestCase;

/**
 * @author mohit
 */
public class ISSOClientTest extends TestCase
{

    String sIssoSep;
    String sSamlRequest;
    String sRelayState;
    String sIname;
    String sUriAssertion;
    String sUriDestination;
    String sSessionID;
    String sArtifact;

    /*
     * @see TestCase#setUp()
     */
    protected void setUp() throws Exception
    {
        super.setUp();
        sIssoSep = "http://isso/";
        sSamlRequest = "enc_saml_request";
        sRelayState = "relaystate";
        sIname = "foo";
        sUriAssertion = "http://assertion";
        sUriDestination = "http://destination";
        sSessionID = "sessionIndex";
        sArtifact = "artifact";
    }

    /*
     * @see TestCase#tearDown()
     */
    protected void tearDown() throws Exception
    {
        super.tearDown();
    }

    /*
     * getRedirectRequestURI()
     */
    public final void testGetRedirectRequestURI()
    {
        String sIssoSEP = sIssoSep;
        String sEncodedSAMLRequest = sSamlRequest;

        String result = sIssoSEP + "?SAMLRequest=" + sEncodedSAMLRequest
                + "&RelayState=" + sRelayState;

        try
        {
            assertEquals(ISSOClient.getRedirectRequestURI(sIssoSEP,
                    sEncodedSAMLRequest, sRelayState), result);
        } catch (Exception e)
        {
            fail("Redirect Request URI is not created correctly");
        }
    }

    /*
     * createSAMLAuthRequest()
     */
    public final void testCreateSAMLAuthRequest()
    {

        String sAssertionConsumerURI = sUriAssertion;
        String sSpProviderID = "providerID";
        String sIBrokerName = "Ibroker";
        String[] sAuthnContext = {"urn:oasis:names:tc:SAML:2.0:ac:classes:Password"};
        String sComparisonType = "exact";

        try
        {
            String authRequest = ISSOClient.createSAMLAuthRequest(sIname,
                    sAssertionConsumerURI, sSpProviderID, true, sIBrokerName,
                    true, sAuthnContext, sComparisonType);

            AuthnRequestDocument docuemnt = AuthnRequestDocument.Factory
                    .parse(authRequest);

            System.out.println(authRequest);
            assertNotNull(authRequest);
            assertTrue(authRequest.contains(sIname));
            assertEquals(docuemnt.getAuthnRequest()
                    .getAssertionConsumerServiceURL(), sAssertionConsumerURI);
            assertEquals(docuemnt.getAuthnRequest().getProviderName(),
                    sIBrokerName);
            assertTrue(docuemnt.getAuthnRequest().getIsPassive());
            assertEquals(docuemnt.getAuthnRequest().getRequestedAuthnContext()
                    .getAuthnContextClassRefArray(0), sAuthnContext);
            assertTrue(authRequest.contains("1"));
        } catch (Exception e)
        {
            fail("fails for reputation = true");
        }
    }

    public final void testCreateSAMLAuthRequestWorksForNoReputation()
    {

        String sAssertionConsumerURI = sUriAssertion;
        String sSpProviderID = "providerID";
        String sIBrokerName = "Ibroker";
        String[] sAuthnContext = {"urn:oasis:names:tc:SAML:2.0:ac:classes:Password"};
        String sComparisonType = "exact";

        try
        {
            String authRequest = ISSOClient.createSAMLAuthRequest(sIname,
                    sAssertionConsumerURI, sSpProviderID, false, sIBrokerName,
                    false, sAuthnContext, sComparisonType);

            AuthnRequestDocument docuemnt = AuthnRequestDocument.Factory
                    .parse(authRequest);

            assertNotNull(authRequest);
            assertTrue(authRequest.contains(sIname));
            assertEquals(docuemnt.getAuthnRequest()
                    .getAssertionConsumerServiceURL(), sAssertionConsumerURI);
            assertFalse(docuemnt.getAuthnRequest().getIsPassive());
            assertEquals(docuemnt.getAuthnRequest().getRequestedAuthnContext()
                    .getAuthnContextClassRefArray(0), sAuthnContext);
            assertTrue(authRequest.contains("0"));
        } catch (Exception e)
        {
            fail("fails for reputation = false");
        }
    }

    /*
     * createSAMLLogoutRequest()
     */
    public final void testCreateSAMLLogoutRequest()
    {
        String sDestinationURL = sUriDestination;
        String sSpProviderID = "providerID";

        try
        {
            String logoutRequest = ISSOClient.createSAMLLogoutRequest(sIname,
                    sSessionID, sSpProviderID, sDestinationURL);

            LogoutRequestDocument document = LogoutRequestDocument.Factory
                    .parse(logoutRequest);

            System.out.println(logoutRequest);
            assertNotNull(document);
            assertNotNull(logoutRequest);
            assertTrue(logoutRequest.contains(sIname));
            assertTrue(logoutRequest.contains(sDestinationURL));
            assertTrue(logoutRequest.contains(sSpProviderID));
            assertTrue(logoutRequest.contains(ISSOClient.REQUEST_REASON));
        } catch (Exception e)
        {
            fail("fails for reputation = false");
        }
    }

    public final void testCreateSAMLLogoutRequestIsUnique()
    {

        String sDestinationURL = sUriDestination;
        String sSpProviderID = "providerID";

        try
        {
            String logoutRequest1 = ISSOClient.createSAMLLogoutRequest(sIname,
                    sSessionID, sSpProviderID, sDestinationURL);
            String logoutRequest2 = ISSOClient.createSAMLLogoutRequest(sIname,
                    sSessionID, sSpProviderID, sDestinationURL);
            assertNotSame(logoutRequest1, logoutRequest2);

        } catch (Exception e)
        {
            fail("Does not generate Unique Logout request");
        }
    }

    /*
     * createSAMLArtifactResolveRequest()
     */
    public final void testCreateSAMLArtifactResolveRequest()
    {
        String sArtifact = "TO4oyNtVH52NixgGGGthsfrnkSM=NaUYlGyCqh1Puar9XHPxHbTnLlQ=1234";
        //ClientMessages.getString("artifact");

        try
        {
            String resolveRequest = ISSOClient
                    .createSAMLArtifactResolveRequest(sArtifact);

            ArtifactResolveDocument.Factory.parse(resolveRequest);
            System.out.println("resolveRequest: " + resolveRequest);

            assertNotNull(resolveRequest);
        } catch (Exception e)
        {
            fail("Does not create artifact resolve request");
        }
    }

    public final void testCreateSAMLArtifactResolveRequestNoDuplicate()
    {
        String sArtifact = "TO4oyNtVH52NixgGGGthsfrnkSM=NaUYlGyCqh1Puar9XHPxHbTnLlQ=1234";

        try
        {
            String resolveRequest1 = ISSOClient
                    .createSAMLArtifactResolveRequest(sArtifact);
            String resolveRequest2 = ISSOClient
                    .createSAMLArtifactResolveRequest(sArtifact);

            assertNotSame(resolveRequest1, resolveRequest2);

            ArtifactResolveType.Factory.parse(resolveRequest1);
        } catch (Exception e)
        {
            fail("Does not create unique artifact resolve request");
        }
    }

    /*
     * getLogoutSatusFromArtifactResponse()
     */
    public final void testGetLogoutSatusFromArtifactResponse()
    {
        String sArtifact = "<urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T16:01:19.921+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:LogoutResponse ID='UI142kjakj234askcvaw3' Version='2.0' Destination='http://idp.com' InResponseTo='223232321' IssueInstant='2006-03-05T17:35:32.896+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:LogoutResponse></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";

        try
        {
            String resolveRequest = ISSOClient
                    .getLogoutSatusFromArtifactResponse(sArtifact);

            assertNotNull(resolveRequest);
            assertTrue(resolveRequest
                    .equals("urn:oasis:names:tc:SAML:2.0:status:Success"));
        } catch (Exception e)
        {
            fail("Does not create artifact resolve request");
        }
    }

    public final void testGetLogoutSatusFromArtifactResponseWorksForInvalid()
    {
        String sArtifact = "INVALID";
        String resolveRequest = null;
        try
        {
            resolveRequest = ISSOClient
                    .getLogoutSatusFromArtifactResponse(sArtifact);

            fail("Does not parse Artifact response correct;y");

        } catch (Exception e)
        {
            assertNull(resolveRequest);
        }
    }

    /*
     * validateSignatureForSAMLResponse()
     */
    public final void testValidateSignatureForSAMLResponse()
    {
        String record = "<urn:LogoutResponse ID='UI142kjakj234askcvaw3' Version='2.0' Destination='http://idp.com' InResponseTo='223232321' IssueInstant='2006-03-05T17:35:32.896+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:LogoutResponse>";//getXML("c:/saml/authResponse.xml");

        try
        {
            assertTrue(ISSOClient.validateSignatureForSAMLResponse(record));
        } catch (Exception e)
        {
            fail("Does not validate Signature correctly");
        }
    }

    /*
     * getAuthnResponseValuesFromArtifactResponse()
     */
    public final void testGetAuthnResponseValuesFromArtifactResponse()
    {
        String xml = "<urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";
        try
        {
            ArtifactResponseDocument artifactResponseDocument = ArtifactResponseDocument.Factory
                    .parse(xml);

            SAMLDataObject dataObject = ISSOClient
                    .getAuthnResponseValuesFromArtifactResponse(artifactResponseDocument
                            .xmlText());

            assertTrue(dataObject.getSAMLStatus().equals(
                    "urn:oasis:names:tc:SAML:2.0:status:Success"));
        } catch (Exception e)
        {
            fail("Does not get correct authn response");
        }
    }

    public final void testGetAuthnResponseValuesFromArtifactResponseWorksForInvalid()
    {
        String xml = "INVALID";
        SAMLDataObject dataObject = null;
        try
        {
            //			ArtifactResponseDocument artifactResponseDocument =
            // ArtifactResponseDocument.Factory
            //					.parse(xml);

            dataObject = ISSOClient
                    .getAuthnResponseValuesFromArtifactResponse(xml);
            fail("Does not get correct authn response");
        } catch (Exception e)
        {
            assertNull(dataObject);
        }
    }

    /*
     * getValuesFromSAMLLogoutResponse()
     */
    public final void testGetValuesFromSAMLLogoutResponse()
    {
        String sLogoutResponse = "<urn:LogoutResponse ID='UI142kjakj234askcvaw3' Version='2.0' Destination='http://idp.com' InResponseTo='223232321' IssueInstant='2006-03-05T17:35:32.896+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:LogoutResponse>";
        try
        {
            assertEquals(ISSOClient.getValuesFromSAMLLogoutResponse(
                    sLogoutResponse, "http://idp.com"),
                    "urn:oasis:names:tc:SAML:2.0:status:Success");
        } catch (Exception e)
        {
            fail("Does not get correctly parse Logout response");
        }
    }

    public final void testGetValuesFromSAMLLogoutResponseWorksForInvalid()
    {
        String sLogoutResponse = "INVALID";
        String response = null;
        try
        {
            response = ISSOClient.getValuesFromSAMLLogoutResponse(
                    sLogoutResponse, "http://idp.com");

            fail("Does not get correctly parse Logout response");
        } catch (Exception e)
        {
            assertNull(response);
        }
    }

    public final void testGetValuesFromSAMLLogoutResponseWorksForNegativeResp()
    {
        String sLogoutResponse = "<urn:LogoutResponse ID='UI142kjakj234askcvaw3' Version='2.0' Destination='http://idp.com' InResponseTo='223232321' IssueInstant='2006-03-05T17:35:32.896+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='NOAUTHNCONTEXT'/></urn:Status></urn:LogoutResponse>";
        String response = null;
        try
        {
            response = ISSOClient.getValuesFromSAMLLogoutResponse(
                    sLogoutResponse, "http://idp.com");
            assertEquals(response, "NOAUTHNCONTEXT");

        } catch (Exception e)
        {
            fail("Does not correctly parse Logout response");
        }
    }

    public final void testGetValuesFromSAMLLogoutResponseWorksForDiffDest()
    {
        String sLogoutResponse = "<urn:LogoutResponse ID='UI142kjakj234askcvaw3' Version='2.0' Destination='http://idp.com' InResponseTo='223232321' IssueInstant='2006-03-05T17:35:32.896+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:LogoutResponse>";
        String response = null;
        try
        {
            response = ISSOClient.getValuesFromSAMLLogoutResponse(
                    sLogoutResponse, "SOMEOTHER");
            fail("Does not correctly parse Logout response");

        } catch (Exception e)
        {
            assertNull(response);
        }
    }

    /*
     * getValuesFromSAMLArtifact()
     */
    public final void testGetValuesFromSAMLArtifact()
    {
        //PASS
        String artifactDocumentXML = "<urn:Artifact xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'>messageIDmessageIDmessageIDmessageIDmessageIDmessageIDl21234</urn:Artifact>";
        try
        {
            ArtifactDocument artifactDocument = ArtifactDocument.Factory
                    .parse(artifactDocumentXML);
            SAMLDataObject dataObject = ISSOClient
                    .getValuesFromSAMLArtifact(artifactDocumentXML);
            assertEquals(dataObject.getArtifact(),
                    "messageIDmessageIDmessageIDmessageIDmessageIDmessageIDl21234");
            assertNotNull(dataObject.getProviderIDHash());

        } catch (Exception e)
        {
            fail("Does not parse saml artifact correctly");
        }
    }

    public final void testGetValuesFromSAMLArtifactFailsForWrongData()
    {
        //PASS
        String artifactDocumentXML = "<urn:Artifact xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'>SAMLLVALUE</urn:Artifact>";
        try
        {
            ArtifactDocument artifactDocument = ArtifactDocument.Factory
                    .parse(artifactDocumentXML);
            SAMLDataObject dataObject = ISSOClient
                    .getValuesFromSAMLArtifact(artifactDocumentXML);
            fail("Does not parse saml artifact correctly");

        } catch (Exception e)
        {
        }
    }

    public final void testGetArtifactResponseFromSOAPEnvelpe()
    {

        try
        {
            //String xml = "<urn:ArtifactResponse
            // InResponseTo='-fb05e90:109cec4e19e:-80000.888739'
            // IssueInstant='2006-03-06T14:39:49.859+05:30'
            // xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response
            // InResponseTo='223232321' Destination='http://idp.com'
            // IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0'
            // ID='UI142kjakj234askcvaw3'
            // xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer
            // NameQualifier='urn:sdf:ijwiers:'
            // xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode
            // Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion
            // IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0'
            // ID='UI2342kjakj234askcvaw3'
            // xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer
            // NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID
            // NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData
            // InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute
            // Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement
            // SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer
            // NameQualifier='name'
            // xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode
            // Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";

            String sArtifactResponseXML = "<urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";

            String sSOAPPrefix = "<?xml version='1.0' encoding='UTF-8'?>"
                    + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                    + "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"><SOAP-ENV:Body>";
            String sSOAPSuffix = "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
            String sSOAPMsg = sSOAPPrefix + sArtifactResponseXML + sSOAPSuffix;

            //		    Reader reader1 = new Reader((Object)sSOAPMsg);
            //		    BufferedReader reader = new BufferedReader();
            //			DocumentBuilder oDocumentBuilder = XMLParserUtils
            //							.getXMLDocBuilder();
            //		    Document oDocument = oDocumentBuilder.parse(sSOAPMsg);
            //		    
            //		    Envelope oEnvelope =
            // Envelope.unmarshall(oDocument.getDocumentElement());

            Envelope oEnvelope = createSOAPEnvelope(sArtifactResponseXML);
            assertNotNull(ISSOClient
                    .getArtifactResponseFromSOAPEnvelpe(oEnvelope));

        } catch (Exception e)
        {
            fail();
        }

    }

    public final void testSendAndReceiveSOAPEnvelopeWorks()
    {
        //String url = "http://meta.resolver.amsoft.co.in/soap.xml";
        //Below is the test value of soap xml to be hosted on the HTTPS url
        //"<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance' xmlns:xsd='http://www.w3.org/1999/XMLSchema'><SOAP-ENV:Body><urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
        String url = "https://localhost:8443/servlets-examples/sessions.html";
        String sArtifactResponseXML = "<urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";
        Envelope oEnvelope = createSOAPEnvelope(sArtifactResponseXML);
        try
        {
            assertNotNull(ISSOClient.sendAndReceiveSOAPEnvelope(oEnvelope, url, "c:/.keystore", "changeit"));
        } catch (Exception e)
        {
            fail("Does not check soap envelop correctly");
        }
    }

    public final void testSendAndReceiveSOAPEnvelopeWorksForAuthSites()
    {
        //String url = "http://meta.resolver.amsoft.co.in/soap.xml";
        //Below is the test value of soap xml to be hosted on the HTTPS url
        //"<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/1999/XMLSchema-instance' xmlns:xsd='http://www.w3.org/1999/XMLSchema'><SOAP-ENV:Body><urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
        String url = "https://login.yahoo.com";
        String sArtifactResponseXML = "<urn:ArtifactResponse InResponseTo='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:39:49.859+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn:Extensions><urn:Response InResponseTo='223232321' Destination='http://idp.com' IssueInstant='2006-03-06T13:04:39.578+05:30' Version='2.0' ID='UI142kjakj234askcvaw3' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status><urn1:Assertion IssueInstant='2006-03-06T13:04:39.734+05:30' Version='2.0' ID='UI2342kjakj234askcvaw3' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'><urn1:Issuer NameQualifier='urn:sdf:ijwiers:'/><urn1:Subject><urn1:NameID NameQualifier='=foo'/></urn1:Subject><urn1:Subject><urn1:SubjectConfirmation><urn1:SubjectConfirmationData InResponseTo=''/></urn1:SubjectConfirmation></urn1:Subject><urn1:AttributeStatement><urn1:Attribute Name='ContactReputationScore'><urn1:AttributeValue>32</urn1:AttributeValue></urn1:Attribute></urn1:AttributeStatement><urn1:AuthnStatement SessionIndex='323ksldjf93'/></urn1:Assertion></urn:Response></urn:Extensions><urn1:Issuer NameQualifier='name' xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Status><urn:StatusCode Value='urn:oasis:names:tc:SAML:2.0:status:Success'/></urn:Status></urn:ArtifactResponse>";
        Envelope oEnvelope = createSOAPEnvelope(sArtifactResponseXML);
        try
        {
            assertNotNull(ISSOClient.sendAndReceiveSOAPEnvelope(oEnvelope, url));
        } catch (Exception e)
        {
            fail("Does not check soap envelop correctly");
        }
    }
    
    /*
     * createSOAPEnvelope()
     */
    public final void testCreateSOAPEnvelope()
    {
        String artifactRespDoc = "<urn:ArtifactResolve Version='2.0' ID='-fb05e90:109cec4e19e:-80000.888739' IssueInstant='2006-03-06T14:25:42.625+05:30' xmlns:urn='urn:oasis:names:tc:SAML:2.0:protocol'><urn1:Issuer xmlns:urn1='urn:oasis:names:tc:SAML:2.0:assertion'/><urn:Artifact>TO4oyNtVH52NixgGGGthsfrnkSM=NaUYlGyCqh1Puar9XHPxHbTnLlQ=1234</urn:Artifact></urn:ArtifactResolve>";

        try
        {
            assertNotNull(ISSOClient.createSOAPEnvelope(artifactRespDoc));
        } catch (Exception e)
        {
            fail("Does not create SOAP envelop");
        }
    }

    public final void testCreateSOAPEnvelopeForWrongData()
    {
        String artifactRespDoc = "INVALID";

        try
        {
            assertNull(ISSOClient.createSOAPEnvelope(artifactRespDoc));
        } catch (Exception e)
        {
            fail("Does not create SOAP envelop");
        }
    }
    /*
     * Method to read XML from file system
     */
    private final String getXML(String filePath)
    {
        String record = null;

        try
        {
            FileReader fr = new FileReader(filePath);
            BufferedReader br = new BufferedReader(fr);

            while ((record = br.readLine()) != null)
            {
            }

        } catch (IOException e)
        {
            return null;
        }

        return record;
    }

    private static final Envelope createSOAPEnvelope(String sXmlArtResDoc)
    {

        Envelope oEnvelope = null;
        try
        {
            ArtifactResponseDocument oArtifactResponseDocument = ArtifactResponseDocument.Factory
                    .parse(sXmlArtResDoc);

            DocumentBuilder oXdb = XMLParserUtils.getXMLDocBuilder();

            Document oDoc = oXdb.newDocument();

            oEnvelope = new Envelope();

            Header oHeader = new Header();

            Vector oBodyEntries = new Vector();

            XmlObject oDocObj = oArtifactResponseDocument;

            Node oW3node = oDocObj.newDomNode();

            Element oElement;

            if (oW3node instanceof Document)
            {
                oDoc = (Document) oW3node;
                oElement = oDoc.getDocumentElement();
            } else
            {
                /**
                 * Ok, much weirdness here -- the owner document exists, and is
                 * registered as our owner, but doesn't actually know about the
                 * child; fix that
                 */
                oDoc = (oW3node).getOwnerDocument();
                oElement = (Element) (oW3node).getFirstChild();
                oDoc.appendChild(oW3node);
            }

            oBodyEntries.add(oElement);
            /**
             * Envelope body
             */
            Body oBody = new Body();

            /**
             * Set body entries in the body
             */
            oBody.setBodyEntries(oBodyEntries);

            /**
             * Set body in the envelope
             */
            oEnvelope.setBody(oBody);

        }//try
        catch (Exception e)
        {

        }//catch

        return oEnvelope;
    }//createSOAPEnvelope() exit
}